#include "timer.h"
#include "fsl_pit.h"


#define TIMER_PIT_BASEADDR PIT
#define TIMER_PIT_CHANNEL  kPIT_Chnl_0
#define PIT_LED_HANDLER    PIT_IRQHandler
#define PIT_IRQ_ID         PIT_IRQn


void timerInit(void)
{
    pit_config_t pitConfig;
    
    /*
     * pitConfig.enableRunInDebug = false;
     */
    PIT_GetDefaultConfig(&pitConfig);

    /* Init pit module */
    PIT_Init(TIMER_PIT_BASEADDR, &pitConfig);

    /* Set timer period for channel 0 */
    PIT_SetTimerPeriod(TIMER_PIT_BASEADDR, TIMER_PIT_CHANNEL, USEC_TO_COUNT(2000U, CLOCK_GetFreq(kCLOCK_PerClk)));

    /* Enable timer interrupts for channel 0 */
    PIT_EnableInterrupts(TIMER_PIT_BASEADDR, TIMER_PIT_CHANNEL, kPIT_TimerInterruptEnable);

    /* Enable at the NVIC */
    EnableIRQ(PIT_IRQ_ID);
    NVIC_SetPriority(PIT_IRQ_ID, 7);
    
    PIT_StartTimer(TIMER_PIT_BASEADDR, TIMER_PIT_CHANNEL);
    
}

extern void ioCheck(void);
void PIT_LED_HANDLER(void)
{
    PIT_ClearStatusFlags(TIMER_PIT_BASEADDR, TIMER_PIT_CHANNEL, kPIT_TimerFlag);
    
    //ioCheck();
    
#if defined __CORTEX_M && (__CORTEX_M == 4U || __CORTEX_M == 7U)
    __DSB();
#endif
}

void timerShutdown(void)
{
    // Turn off PIT: MDIS = 1, FRZ = 0
    PIT->CHANNEL[1].TCTRL = 0; // stop timer 1
    PIT->CHANNEL[0].TCTRL = 0; // stop timer 1
    PIT->CHANNEL[1].LDVAL = 0;
    PIT->CHANNEL[0].LDVAL = 0;
    PIT->MCR |= PIT_MCR_MDIS_MASK;
}
